package com.gupao.dubbo.netty.server.register;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;

public class RegisterImpl implements IRegister {

    private final CuratorFramework curatorFramework;

    {
        curatorFramework = CuratorFrameworkFactory.builder().connectString(ZKConfig.ZK_CONNECTOR_STR).sessionTimeoutMs(60000000).retryPolicy(new ExponentialBackoffRetry(1000, 10)).build();
        // zookeeper失连监听器，可以在监听器中重建临时节点
        // curatorFramework.getConnectionStateListenable().addListener(new ZKConnectionStateListener());
        curatorFramework.start();
    }

    public void register(String serviceName, String serviceAddress) {
        String servicePath = ZKConfig.REGISTOR_PATH + "/" + serviceName;
        try {
            if (curatorFramework.checkExists().forPath(servicePath) == null) {
                curatorFramework.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath(servicePath, "0".getBytes());
            }
            String addressPath = servicePath + "/" + serviceAddress;
            String rp = curatorFramework.create().withMode(CreateMode.EPHEMERAL).forPath(addressPath, "0".getBytes());
            System.out.println("服务注册成功! " + rp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
